package com.minimalist.basic.config.bucket;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author 11987
 */
@Component
@Slf4j
public class RateLimitMetrics {
    private final MeterRegistry meterRegistry;
    private final Counter rateLimitExceeded;
    private final Counter requestsTotal;
    private final Gauge currentLimit;

    public RateLimitMetrics(MeterRegistry registry,
                            RateLimitConfigProvider configProvider) {
        this.meterRegistry = registry;

        this.rateLimitExceeded = Counter.builder("rate_limit.exceeded")
                .description("超过速率限制的事件数")
                .tag("type", "exceeded")
                .register(registry);

        this.requestsTotal = Counter.builder("rate_limit.requests")
                .description("处理的请求总数")
                .tag("type", "total")
                .register(registry);

        this.currentLimit = Gauge.builder("rate_limit.current",
                        configProvider,
                        this::getCurrentLimit)
                .description("当前速率限制值")
                .tag("type", "limit")
                .register(registry);

    }

    public Timer.Sample startTimer() {
        return Timer.start();
    }

    public void stopTimer(Timer.Sample sample, String path, String method, boolean rateLimited) {
        Timer timer = Timer.builder("rate_limit.request.duration")
                .description("通过速率限制器请求持续时间")
                .tags("path", path, "method", method,
                        "rate_limited", String.valueOf(rateLimited),
                        "component", "rate_limiter")
                .register(meterRegistry);
        sample.stop(timer);
    }

    public void incrementRateLimitExceeded() {
        rateLimitExceeded.increment();
    }

    public void recordRequest() {
        requestsTotal.increment();
    }

    private double getCurrentLimit(RateLimitConfigProvider provider) {
        return provider.getRateLimitConfig().getLimit();
    }

    public Map<String, Number> getCurrentMetrics() {
        log.info("当前速率限制值：{}，处理的请求总数：{}，超过速率限制的事件数：{}"
                , currentLimit.value(), requestsTotal.count(), rateLimitExceeded.count());
        return Map.of("rateLimitExceeded", rateLimitExceeded.count(),
                "totalRequests", requestsTotal.count(),
                "currentLimit", currentLimit.value());
    }
}